package pe.gob.osinergmin.interfase_siaf.dac.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import pe.gob.osinergmin.interfase_siaf.dac.dao.CicloDao;
import pe.gob.osinergmin.interfase_siaf.dac.domain.Ciclo;

@Repository("cicloDao")
public class CicloDaoImpl implements CicloDao{
	
	private final Log logger = LogFactory.getLog(getClass());
	
	
	private NamedParameterJdbcTemplate jdbcParameterTemplateData;	
	private JdbcTemplate jdbcTemplateData;	
	
	
	
	@Autowired
	public void SetDataSource(DataSource dataSourceData){
		this.jdbcTemplateData = new JdbcTemplate(dataSourceData);
		this.jdbcParameterTemplateData = new NamedParameterJdbcTemplate(dataSourceData);
		
	}
	
	/**DECLARACION DE SQL**/
	private static final String SQL_SELECT_CICLO ="SELECT * FROM ciclo ";
	private static final String SQL_SELECT_CICLO_PARAMETER ="SELECT * FROM ciclo WHERE ciclo =:ciclo";
	private static final String SQL_SELECT_CICLO_PARAMETER1 ="SELECT * FROM ciclo WHERE nombre =:nombre";

	private static final String SQL_SELECT_CICLO_PARAMETER2 ="SELECT COUNT(ciclo) FROM ciclo WHERE ciclo =:ciclo";
	
	
	@Override
	public List<Ciclo> listarCiclo() {
		logger.info("Ingresando a listar ciclos"); 
		RowMapper<Ciclo> lista = ParameterizedBeanPropertyRowMapper.newInstance(Ciclo.class);
		return this.jdbcTemplateData.query(SQL_SELECT_CICLO, lista);
	}
	@Override
	public List<Ciclo> listarCicloParameter(Ciclo ciclo) {
		logger.info("Ingresando a listar ciclos parameters"); 
		SqlParameterSource parameters = new BeanPropertySqlParameterSource(ciclo);
		RowMapper<Ciclo> lista = ParameterizedBeanPropertyRowMapper.newInstance(Ciclo.class);
		if(StringUtils.isNoneBlank(ciclo.getCiclo())){ 
			return this.jdbcParameterTemplateData.query(SQL_SELECT_CICLO_PARAMETER, parameters, lista);	
		}else if(StringUtils.isNoneBlank(ciclo.getNombre())){
			return this.jdbcParameterTemplateData.query(SQL_SELECT_CICLO_PARAMETER1, parameters, lista);	
		}else{
			return null;
		}			
	}
	
	
	/**IMPLEMENTACION DE METODOS*/	
	@Override
	public int verificarCiclo(Ciclo c) throws Exception {		 
		SqlParameterSource parameters = new BeanPropertySqlParameterSource(c);		
	    return this.jdbcParameterTemplateData.queryForInt(SQL_SELECT_CICLO_PARAMETER2, parameters);	
	}



}
